const app = getApp();
Page({
  data: {
    chose: 0,
    defaultIndex: -1,
    addressList: [],
  },
  onLoad: function (options) {
    this.setData({
      options: options, 
    })
  },
  onShow: function () {
    this.getInfo();
  },
  getInfo(){
    let that = this;
    app.request('address/addressList',{},'GET',false,function(res){
      that.setData({
        pageShow: true,
        addressList: res.data.data,
      })
    })
  },
  getFormid(e) {
    app.getFormid(e);
  },
  //选择默认地址
  chooseDefaultIndex: function (e) {
    let that = this;
    let addressList = that.data.addressList;
    let address_id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    app.request('address/setDefault', { address_id },'GET',false,function(res){
      wx.showToast({
        title: '设置成功',
        mask: true,
      })
      addressList.map((v,k)=>{
        v.is_default = index==k?1:0;
      })
      let addItem = addressList[index];
      addressList.splice(index,1);
      addressList.unshift(addItem);
      that.setData({
        addressList: addressList
      })
    })

  },
  //删除
  del: function (e) {
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要删除吗?',
      showCancel: true,
      success: function (res) {
        if(res.confirm){
          let index = e.currentTarget.dataset.index;
          let addressList = that.data.addressList;
          let address_id = addressList[index].id;
          app.request('address/delete', { address_id }, 'GET', false, function (res) {
            wx.showToast({
              title: '已删除',
            })
            that.getInfo();
          })
        }
      }
    })
  },
  editor: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let addressList = that.data.addressList;
    let id = addressList[index].id;
    wx.navigateTo({
      url: '/pages/address/addressAdd/addressAdd?id=' + id,
    })
  },
  addressAdd: function () {
    wx.navigateTo({
      url: "/pages/address/addressAdd/addressAdd"
    })
  },
  toback: function (e) {
    let that = this;
    if(that.data.options.from == 'order'){
      let index = e.currentTarget.dataset.index;
      let addressList = that.data.addressList;
      wx.setStorageSync('addressChoose', addressList[index]);
      wx.navigateBack({
        delta: 1,
      })
    }
  },
  onShareAppMessage(){
    return{
      path: '/pages/index/index'
    }
  }
})